import BaseComponent from "../../Game/Base/BaseClass/BaseComponent";
import FPJDefine from "../../Game/FPJ/Prefabs/FPJDefine";
import ScrollViewPlus from "../../lib/ScrollViewPlus";
import LoadingDialog from "./LoadingDialog";
import TableItemPrefab, { TableItemData } from "./TableItemPrefab";
import TableItemTypePrefab, { TableItemTypeData } from "./TableItemTypePrefab";
const { ccclass, property } = cc._decorator;

@ccclass
export default class SmallFPJTableView extends BaseComponent {
	@property(ScrollViewPlus)
	scrollViewPlus: ScrollViewPlus = null;

	@property(cc.Prefab)
	scrollViewItemPrefab: cc.Prefab = null;
	@property(cc.Prefab)
	scrollViewTypeItemPrefab: cc.Prefab = null;
	@property(cc.Prefab)
	RoomButtonPrefab: cc.Prefab = null;
	@property(cc.Node)
	RoomButtonParent: cc.Node = null;
	@property(LoadingDialog)
	loadingDialog: LoadingDialog = null;

	@property(cc.SpriteFrame)
	choiceSpriteFrame = [];
	@property(cc.SpriteFrame)
	unchoiceSpriteFrame = [];

	@property(cc.Component.EventHandler)
	touchend: cc.Component.EventHandler[] = [];

	_alltable = [];

	_currentRoomLevel = 0;
	onLoad() {
		this.loadingDialog.hide();
		cc.vv.eventCustom.on("TableItemShow", this.TableItemShow.bind(this), this.node);
		cc.vv.eventCustom.on("resetTable", ()=>{
			this.onclickback()
		}, this.node);
		
	}
	onEnable(){
		for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
			let p = this.scrollViewPlus.content.children[t];
			if (p.istable) {
				p.getComponent(TableItemPrefab).updataTableData()
			}
		}
	}
	onDestroy() {
	}
	start() {
		this.createAllTable()
		for (let s = 0; s < FPJDefine.room_list.length; s++) {
			let p = cc.instantiate(this.RoomButtonPrefab);
			p.getComponent("RoomButton").initData(s, this.choiceSpriteFrame[s], this.unchoiceSpriteFrame[s], this.touchend,2,FPJDefine.room_list[s].room_id)
			p.parent = this.RoomButtonParent;
		}
		
	}

	scrolltoOffsetByLevel(level) {
		let s = level;
		let offx = 0;
		//跳转到高级  查找高级的item坐标
		for (var t = 0; t < this.scrollViewPlus.content.childrenCount; t++) {
			let p = this.scrollViewPlus.content.children[t];
			if (p.istable) {
				if (p.getComponent(TableItemPrefab).getData().RoomLevel >= level) {
					offx = p.x - 200;
					break;
				}
			}
		}
		console.log("滚动到s ", s, this.scrollViewPlus.getMaxScrollOffset(), offx)
		this.scrollViewPlus.scrollToOffset(cc.v2(offx, 0), 0.2);
	}

	TableItemShow(args) {
		if (this._currentRoomLevel != args[0].RoomLevel) {
			this._currentRoomLevel = args[0].RoomLevel;
			console.log("table等级改变了。。。", this._currentRoomLevel)
			cc.vv.eventCustom.emit("showsp", this._currentRoomLevel)
		}
	}

	async createAllTable() {
		this.loadingDialog.show();
		this.scrollViewPlus.content.removeAllChildren();
		let count = 44;
		await this.executePreFrame(this._getItemGenerator(FPJDefine.table_list), 1);
		// 在创建好子节点之后，先手动调用一次DC优化，触发当前在可视区域内的节点的进入逻辑
		// 后续的ScrollView滚动时，内部自动回调
		this.scrollViewPlus.optDc();
		this.loadingDialog.hide();
	}

	/**
	 * 分帧执行 Generator 逻辑
	 *
	 * @param generator 生成器
	 * @param duration 持续时间（ms），每次执行 Generator 的操作时，最长可持续执行时长。假设值为8ms，那么表示1帧（总共16ms）下，分出8ms时间给此逻辑执行
	 */
	private executePreFrame(generator: Generator, duration: number) {
		return new Promise((resolve, reject) => {
			let gen = generator;
			// 创建执行函数
			let execute = () => {
				// 执行之前，先记录开始时间
				let startTime = new Date().getTime();

				// 然后一直从 Generator 中获取已经拆分好的代码段出来执行
				for (let iter = gen.next(); ; iter = gen.next()) {
					// 判断是否已经执行完所有 Generator 的小代码段，如果是的话，那么就表示任务完成
					if (iter == null || iter.done) {
						resolve();
						return;
					}

					// 每执行完一段小代码段，都检查一下是否已经超过我们分配的本帧，这些小代码端的最大可执行时间
					if (new Date().getTime() - startTime > duration) {
						// 如果超过了，那么本帧就不在执行，开定时器，让下一帧再执行
						this.scheduleOnce(() => {
							execute();
						});
						return;
					}
				}
			};

			// 运行执行函数
			execute();
		});
	}

	private *_getItemGenerator(data: { roomid: string; tableid: number;level:number }[]) {
		let t = data.length;
		let currentlevel = -1;
		for (let i = 0; i < t; i++) {
			let level =  data[i].level
			if(currentlevel!=level){
				let itemNode = cc.instantiate(this.scrollViewTypeItemPrefab);
				itemNode.parent = this.scrollViewPlus.content;
				itemNode.istable = false;
				itemNode.getComponent(TableItemTypePrefab).bindData({
					RoomLevel: level,
				});
				currentlevel= level
			}
			yield this._initScrollViewItemPrefab({
				tableData: data[i],
				playername: String(i),
				RoomLevel: level,
				type:2,
			});
		}
		cc.vv.eventCustom.emit("showsp",0)
		this.scrolltoOffsetByLevel(0);
	}
	private _initScrollViewItemPrefab(data: TableItemData) {
		let itemNode = cc.instantiate(this.scrollViewItemPrefab);
		itemNode.istable = true;
		itemNode.parent = this.scrollViewPlus.content;
		itemNode.getComponent(TableItemPrefab).bindData(data);
	}

	//进入初级场次
	onClickchoicelowLevel(level) {
		cc.vv.audioUtil.playSound("Hall/sound/button_onclicked");
		this.scrolltoOffsetByLevel(level);
	}
	onclickback(){
		this.node.active = false;
	}
}
